package com.ggh.controller;
import	java.util.HashMap;
import java.util.Random;
import	java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ggh.config.Shiro.LoginType;
import com.ggh.config.Shiro.UserLoginToken;
import com.ggh.entity.Menu;
import com.ggh.entity.TypeBean;
import com.ggh.entity.User;
import com.ggh.service.MenuService;
import com.ggh.service.UserService;
import com.ggh.util.JsonUtils;
import com.ggh.vo.Body;
import com.ggh.vo.Meta;
import com.ggh.vo.ShowMenuVo;
import com.ggh.vo.UserToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author ： jsq
 * @date ：2019/10/14 23:20
 * @description : 登陆
 * @path : com.ggh.controller.LoginController
 * @modifiedBy ：
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService ;
    @Autowired
    private  MenuService menuService;
    /**
    * @description :登录界面
    * @date : 2019/10/30 13:59
    * @author : jj
    */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String  login(){
        return "admin/login";
    }
    /**
    * @description :后台登录
    * @param username 
    * @param password 
    * @param model
    * @date : 2019/10/30 14:00
    * @author : jj
    */
    @RequestMapping(value = "/login", method = RequestMethod.POST )
    @ResponseBody
    public Body login(HttpSession session,@RequestParam("username") String username, @RequestParam("password") String password , Model model ) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UserLoginToken token = new UserLoginToken(LoginType.USER_PASSWORD,username, password);
        // 执行认证登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
          return Body.newInstance(405,"未知账户");
        } catch (IncorrectCredentialsException ice) {
            return Body.newInstance(405,"密码不正确");
        } catch (LockedAccountException lae) {
            return Body.newInstance(405,"账户已锁定");
        } catch (ExcessiveAttemptsException eae) {
            return Body.newInstance(405,"用户名或密码错误次数过多");
        } catch (AuthenticationException ae) {
            return Body.newInstance(405,"用户名或密码不正确");
        }
        if (subject.isAuthenticated()) {
            User principal = (User) subject.getPrincipal();
            session.setAttribute("icon", StringUtils.isBlank(principal.getAvatarurl()) ? "/static/admin/img/face.jpg" : principal.getAvatarurl());
            return Body.newInstance(Meta.CODE_200,"/index");
        } else {
            token.clear();
            return Body.newInstance(405,"登录失败！");

        }
    }

    /**
     * 进入主题
     * @param map
     * @return
     */
    @GetMapping("admin/main")
    public String main(ModelMap map){
        return "admin/main";
    }
    /***
     * 获得用户所拥有的菜单列表
     * @return
     */
    @GetMapping("/admin/user/getUserMenu")
    @ResponseBody
    public List<ShowMenuVo> getUserMenu(){
        List<ShowMenuVo> list = menuService.getAlls();
        return list;
    }
    /**
    * @description :微信登录
    * @param code 
    * @date : 2019/10/30 14:00
    * @author : jj
    */
    @RequestMapping("/wechatLogin")
    @ResponseBody
    public UserToken wechatLogin(String code){
      /*// 此处假装code分别是username、password
        UserLoginToken token = new UserLoginToken(LoginType.WECHAT_LOGIN, code, code, code);
        //登录不在该处处理，交由shiro处理
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
      if (subject.isAuthenticated()) {
          List<User> list = userService.list(new QueryWrapper<>(null));
           Map<Integer, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getIsLogin));
        System.out.println(collect);
           List<User> users = collect.get(0);
        System.out.println(users);
           Integer a=users.size();
           Random rand = new Random();
           int random=rand.nextInt(a);
           if (random>2){
               random=random-2;
           }
           User user = users.get(random);
           user.setIsLogin(1);
           boolean b = user.updateById();
           return b ? UserToken.newInstance(user.getUserid(), TypeBean.LoginSucess, "", TypeBean.SUCCESS) :
                   UserToken.newInstance(0, TypeBean.LoginError, "", TypeBean.SUCCESS);*/
      // }
       return  UserToken.newInstance(Integer.valueOf(code), TypeBean.LoginSucess, "", TypeBean.SUCCESS);
    }
    @RequestMapping("/hall")
    @ResponseBody
    public UserToken hall(Integer userid){
      User user = userService.getById(userid);
        //用户没找到
        if(user==null) {
            return UserToken.newInstance(user.getUserid(),TypeBean.LoginError,"",TypeBean.ERROR);
        }else {
            return UserToken.newInstance(user.getUserid(),TypeBean.EnterHall, user,TypeBean.ERROR);
        }
    }
    /**
     * @description :跳转到主页
     * @date : 2019/10/21 15:39
     * @author : jj
     */
    @RequestMapping(value = "/index" , method = RequestMethod.GET)
    public String index(){
        return "admin/index";
    }
    @PostMapping("/logout")
    @ResponseBody
    public UserToken logout(Integer userid){
        User byId = userService.getById(userid);
        if (byId!=null){
            byId.setIsLogin(0);
            boolean b = byId.updateById();
            return b? UserToken.newInstance(0,"HallExit","",TypeBean.SUCCESS)
                    :UserToken.newInstance(0,"ERROR","",TypeBean.ERROR);
        }
        return  UserToken.newInstance(0,"ERROR","",TypeBean.ERROR);
    }


   @GetMapping("logout")
    public  String logout(){
        SecurityUtils.getSubject().logout();
        return "admin/login";
    }
}
